from flask import session
from sqlalchemy import Column,String,create_engine,MetaData,Table,func,event,exc
from sqlalchemy.orm import sessionmaker,scoped_session
from sqlalchemy.types import *
from sqlalchemy.ext.declarative import declarative_base
import os

# 数据库结构的实例化
base = declarative_base()

# 创建链接引擎
engine = create_engine(
    "mysql+pymysql://root:MySQLPass2022@127.0.0.1:3306/biquge?charset=utf8mb4",pool_recycle=300
)

metadata = MetaData(engine)


metadata = MetaData(engine)
import datetime


@event.listens_for(engine, "connect")
def connect(dbapi_connection, connection_record):
    connection_record.info['pid'] = os.getpid()


@event.listens_for(engine, "checkout")
def checkout(dbapi_connection, connection_record, connection_proxy):
    pid = os.getpid()
    if connection_record.info['pid'] != pid:
        connection_record.connection = connection_proxy.connection = None
        raise exc.DisconnectionError(
            "Connection record belongs to pid %s, "
            "attempting to check out in pid %s" %
            (connection_record.info['pid'], pid)
        )

######
class chapters(base):
    __tablename__ = "chapters"
    id = Column(Integer,primary_key = True,autoincrement="auto")
    chapter_name = Column(String)




####

SessionType = scoped_session(sessionmaker(bind=engine, expire_on_commit=False))


def GetSession():
    return SessionType()


from contextlib import contextmanager


@contextmanager
def session_scope():
    session = GetSession()
    try:
        yield session
        session.commit()
    except:
        session.rollback()
        raise
    finally:
        session.close()



